package cn.worldyao.homework;

import cn.worldyao.homework.entity.Student;
import cn.worldyao.homework.entity.Teachers;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.RandomStringUtils;


import javax.servlet.http.HttpSession;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.UUID;

/**
 * @author yaozi
 */
public class Tools {

    public static String[] chars = new String[]{"a", "b", "c", "d", "e", "f",
            "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s",
            "t", "u", "v", "w", "x", "y", "z", "0", "1", "2", "3", "4", "5",
            "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "I",
            "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V",
            "W", "X", "Y", "Z"};

    public static String USER_PASS = "USER_PASS";
    public static String USER_NOT_EXIST = "USER_NOT_EXIST";
    public static String USER_UN_PASS = "USER_UN_PASS";

    /**
     * 生成短8位UUID
     *
     * @return
     */
    public static String UUID8() {
        StringBuilder shortBuffer = new StringBuilder();
        String uuid = UUID.randomUUID().toString().replace("-", "");
        for (int i = 0; i < 8; i++) {
            String str = uuid.substring(i * 4, i * 4 + 4);
            int x = Integer.parseInt(str, 16);
            shortBuffer.append(chars[x % 0x3E]);
        }
        return shortBuffer.toString();
    }


    public static String MD5Pwd(String userPassword, String userSalt) {
        //可用户注册、登录 时使用
        // 加密算法MD5
        // salt盐 username + salt
        // 迭代次数 加密2次
        return DigestUtils.md5Hex(DigestUtils.md5Hex(userPassword + userSalt) + userSalt);
    }

    public static String getSalt8() {
        return RandomStringUtils.randomAlphanumeric(8);
    }


    public static LocalDateTime DateTrans(String date) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
        Date time = sdf.parse(date);
        return time.toInstant()
                .atZone(ZoneId.systemDefault())
                .toLocalDateTime();
    }

    public static boolean userIsStudent(HttpSession session) {
        Object o = session.getAttribute("user");
        if (o != null) {
            return o instanceof Student;
        }
        return false;
    }

    public static boolean userIsTeacher(HttpSession session) {
        Object o = session.getAttribute("user");
        if (o != null) {
            return o instanceof Teachers;
        }
        return false;
    }

}
